import time
from machine import UART
from fpioa_manager import fm

# 初始化串口
fm.register(7, fm.fpioa.UART1_RX, force=True)  # 注意这里使用RX引脚
uart = UART(UART.UART1, 115200, 8, 0, 1, timeout=1000, read_buf_len=4096)

# 物品名称列表
labels = ["xuebi", "kele", "fenda", "maidong", "asamu"]

# 解析数据帧函数
def parse_data(data):
    """解析接收到的数据帧"""
    if len(data) < 8 or data[0] != 0x2C or data[1] != 0x12 or data[7] != 0x5B:
        return None

    return {
        "xuebi": data[2],
        "kele": data[3],
        "fenda": data[4],
        "maidong": data[5],
        "asamu": data[6]
    }

print("Waiting for data...")
last_counts = {label: 0 for label in labels}

while True:
    if uart.any():
        data = uart.read()
        if data:
            # 查找有效数据帧
            start_index = -1
            for i in range(len(data) - 7):
                if data[i] == 0x2C and data[i+1] == 0x12 and data[i+7] == 0x5B:
                    start_index = i
                    break

            if start_index != -1:
                frame = data[start_index:start_index+8]
                counts = parse_data(frame)

                if counts:
                    print("\n--- New Detection Results ---")
                    for label in labels:
                        if counts[label] != last_counts[label]:
                            print(f"{label}: {counts[label]}")
                            last_counts[label] = counts[label]

    # 添加短暂延迟防止CPU过载
    time.sleep_ms(100)
